package org.example.security.config;

import cn.hutool.core.util.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.example.core.constant.TokenConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author 小杰_cc
 * @version 1.0
 */

/**
 * feign配置防止请求头丢失
 */
@Configuration
public class MyFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    String userId = request.getHeader(TokenConstants.USER_ID);
                    if (StrUtil.isNotBlank(userId)){
                        requestTemplate.header(TokenConstants.USER_ID,userId);
                    }
                    String userName = request.getHeader(TokenConstants.USER_NAME);
                    if (StrUtil.isNotBlank(userId)){
                        requestTemplate.header(TokenConstants.USER_ID,userName);
                    }
                }
            }
        };
        return requestInterceptor;
    }
}